using Avalonia.BiliBili.Libs.Models.View;
using Avalonia.BiliBili.ViewModels;
using Avalonia.Controls;
using Avalonia.Extensions.Event;
using Bilibili.Common;
using Bilibili.Model.Rank;
using Bilibili.WebClient.Api;
using DynamicData;
using PCLUntils.IEnumerables;
using PCLUntils.Objects;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Avalonia.BiliBili.Windows
{
    public partial class RankWindow : WindowBase
    {
        private ChannelClient Client { get; }
        private RankViewModel ViewModel { get; }
        public RankWindow()
        {
            InitializeComponent();
            Client = new ChannelClient();
            ViewModel = new RankViewModel();
        }
        protected override void AfterInitializeComponent()
        {
            RunOnUiThread(async () =>
            {
                DataContext = ViewModel;
                ViewModel.InitCategory();
                await LoadDataAsync();
            });
        }
        public void OnTabSelectionChanged(object? sender, SelectionChangedEventArgs e)
        {
            RunOnUiThread(async () =>
            {
                if (e.AddedItems.FindItem(0) is TabControlItem<RankItemModel> model)
                {
                    ViewModel.Current = model.Tag.ToInt32();
                    await LoadDataAsync();
                }
            });
        }
        public void OnItemClick(object sender, ViewRoutedEventArgs e)
        {
            if (e.ClickItem is ListBoxItem item && item.Content is InfoModel info)
            {

            }
        }
        private async Task LoadDataAsync()
        {
            var category = ViewModel.Categories.ElementAt(ViewModel.Current);
            if (!category.HasLoad)
            {
                var result = await Client.GetRank(category.Id, category.Tag.ToString());
                if (result.IsSuccess())
                {
                    var model = result.Data;
                    if (model != null)
                    {
                        var item = ViewModel.Items.FirstOrDefault(x => x.Tag.ToInt32() == category.Id);
                        if (item != null)
                        {
                            var ls = model.Data["list"].ToObject<List<RankItemModel>>();
                            item.Nodes.AddRange(ls);
                        }
                    }
                }
                category.HasLoad = true;
            }
        }
    }
}